<?php require_once(dirname(__FILE__) . '/../../include/config.inc.php');
header('Content-type: application/json;charset=utf-8');
$dosql->Execute("SELECT `id` FROM `#@__order` WHERE  is_delete=0 ", 6);
$count_all = $dosql->GetTotalRow(6); //所有工单

$dosql->Execute("SELECT `id` FROM `#@__order` WHERE `jindu`=1  AND is_delete=0 ", 1);
$count1 = $dosql->GetTotalRow(1); //等待受理

//受理中的工单
$dosql->Execute("SELECT `id` FROM `#@__order` WHERE jindu<5   AND jindu>0  AND is_delete=0 ", 88);
$doing = $dosql->GetTotalRow(88); //等待受理

// 工单的完成率
//1、 当天的派单数量
$sql_today_all = "SELECT count(id) as a  FROM `#@__order`  WHERE  FROM_UNIXTIME(`post_time`,'%Y%m%d')=DATE_FORMAT(CURDATE(),'%Y%m%d')  AND is_delete=0  AND jindu!=0  ";
$dosql->Execute($sql_today_all,8);
while($order=$dosql->GetArray(8)){
    $cishu_today=$order['a'];
};
$sql_today_ok = "SELECT count(id) as a  FROM `#@__order`  WHERE  FROM_UNIXTIME(`post_time`,'%Y%m%d')=DATE_FORMAT(CURDATE(),'%Y%m%d')  AND is_delete=0  AND jindu>'4'  ";
$dosql->Execute($sql_today_ok,9);
while($order=$dosql->GetArray(9)){
    $cishu_today_ok=$order['a'];
};
if($cishu_today_ok>0  ){
    $wanchenglv=round(($cishu_today_ok/$cishu_today)*100,2);
}else{
    $wanchenglv=0;
}

$dosql->Execute("SELECT `id` FROM `#@__order` WHERE `jindu`>1 and  `jindu`<5  AND is_delete=0 ", 2);
$count2 = $dosql->GetTotalRow(2); //受理中

$count = array('all' => $count_all, 'waiting' => $count1, 'doing' => $count2, 'working' => $wanchenglv);

//地图
$map=[];
// 签到 接单 数据
$sql = "SELECT f.* ,j.dataname as jinduname,o.truename as truename , o.address as address, o.school as school,o.mobile as mobile,o.post_time as post_time,o.manageid as manageid FROM `#@__order_log` as f
left join `#@__order`  as o on o.id=f.orderid  
left join `#@__cascadedata`  as j on j.datavalue=f.jindu  
WHERE  j.datagroup='jindu'  AND   o.is_delete=0  AND  f.latitude!='' AND f.qiandao='true'  AND  f.jindu='4'  AND o.jindu>0  AND o.jindu<5  ";

$dosql->Execute($sql,9);
while($row2 = $dosql->GetArray(9))
{
    $map_item['latlngs']=$row2['latitude'].",".$row2['longitude'];
    $map_item['lat']=$row2['latitude'];
    $map_item['lng']=$row2['longitude'];
    if($row2['qiandao']=='true'){
        $row2['jindu']='qian';
    }
    if($row2['jiedan']=='true'){
        $row2['jindu']='jie';
    }
    $map_item['jindu']=$row2['jindu'];

    //获取工程师
    $m_str="";
    if($row2['manageid']!=""){
        $m_manageid=explode(",",$row2['manageid']);
        foreach ($m_manageid as $key=>$val){
            $m_str.=" ".getManage($val);
        }
    }
    $map_item['manageids']=$m_str;


    $map[]=$map_item;
}


// 工程 签到 接单 数据
$sql2 = "SELECT f.*,o.truename as truename , o.address as address, o.school as school,o.mobile as mobile,o.post_time as post_time,o.manageid as manageid,o.apply_device,o.id as orderid FROM (SELECT *  FROM `#@__project_log` where latitude!='' and  signIn='1'
  ORDER BY id DESC limit 1000)  f
left join `#@__project`  as o on o.id=f.orderid  
WHERE  o.is_delete=0   AND o.jindu>0  AND o.jindu<5  group by f.orderid  order by f.id ";

$dosql->Execute($sql2,9);
while($row2 = $dosql->GetArray(9))
{
    $map_item['latlngs']=$row2['latitude'].",".$row2['longitude'];
    $map_item['lat']=$row2['latitude'];
    $map_item['lng']=$row2['longitude'];
    if($row2['signIn']=='1'){
        $row2['jindu']='qian';
    }

    $map_item['jindu']=$row2['jindu'];

    //获取工程师
    $m_str="";
    if($row2['manageid']!=""){
        $m_manageid=explode(",",$row2['manageid']);
        foreach ($m_manageid as $key=>$val){
            $m_str.=" ".getManage($val);
        }
    }
    $map_item['manageids']=$m_str;




    $map[]=$map_item;
}



// 工单列表
$sql = "SELECT f.*,j.dataname as jinduname FROM `#@__order` as f
left join `#@__cascadedata`  as j on j.datavalue=f.jindu  
WHERE j.datagroup='jindu'  AND f.jindu>0 AND f.is_delete=0   order by f.id desc  limit 9   ";
$dosql->Execute($sql,8);
while($row = $dosql->GetArray(8))
{

    $m_truename="";
    if(!empty($row['manageid'])){
        $m_str=$row['manageid'];
        $m_arr=explode(",",$m_str);
        foreach($m_arr as $key=>$val){
            $m_truename.=" ".getManage($val);
        }
    }


    $order_list[]=array(
        'renwu'=>getRepairMode($row['apply_device']),
        'truename'=>$m_truename,
        'school'=>$row['school'],
        'content'=>ReStrLen($row['content'],26),
        'jindu'=>$row['jinduname'],
        'id'=>$row['id']
    );

}


//报修的设备类型
$sql = "SELECT count(o.id) as a,o.apply_device,t.title 
FROM `#@__order` as o 
left join   `#@__task` as t
on o.apply_device=t.id
WHERE  o.is_delete=0  group by o.apply_device ";
$dosql->Execute($sql,7);
$pie_count=$dosql->GetTotalRow(7);
while($order=$dosql->GetArray(7)){
    $typename=$order['title'];
    $cishu=$order['a'];
    $order_type[]=array('typename'=>$typename,'cnt'=>$cishu);
}


//服务星级
//当月完成工单数量
$managelist=array();
$dosql->Execute("SELECT *  FROM `#@__user`  WHERE level='3' and isreport=1   ",1);
while($user_arr=$dosql->GetArray(1)){
    $mid=$user_arr['id'];
    $m_name=$user_arr['truename'];
    $fee=getFeeThisMonth($mid);
    $sql_0 = "SELECT count(id) as a  FROM `#@__order`   WHERE   FIND_IN_SET('$mid',manageid)    AND  FROM_UNIXTIME(`post_time`,'%Y%m')=DATE_FORMAT(CURDATE(),'%Y%m')  AND is_delete=0    AND jindu!=0 ";
    $dosql->Execute($sql_0,2);
    while($order=$dosql->GetArray(2)){
        $cishu=$order['a'];
    }
    $managelist[]=array('truename'=>$m_name,'cishu'=>$cishu,'fee'=>$fee);
}
//对数组进行 排序
array_multisort(array_column($managelist,'fee'),SORT_DESC,$managelist);


//获取每月 报修数量
$year_data=array();
$year_arr=getTimeAndCenters();
for ($i = 0; $i < 12; $i++) {	// 年
    $ff_d=$year_arr[$i];
    $firstday =$year_arr[$i]."-01";
    $lastday = getNextMonth($firstday);
    $lastday=$lastday['sdate'];
    $start = strtotime($firstday . " 00:00:00");
    $end = strtotime($lastday . " 00:00:00");
    $jiedan = $dosql->GetOne("SELECT COUNT(*) AS `count` FROM `#@__order` WHERE post_time > $start AND post_time < $end  and is_delete=0 ");
    $year_data[] = array('month'=>$ff_d,'num'=>$jiedan['count']);
}

$year_data=array_reverse($year_data);


//人员动态
//获取人员流水
$dongtai = "";
$order_dongtai=[];
$today = date("Y-m-d", time());
$s_time = strtotime($today);
$sql = "select * from `#@__order_log`  where op_time>'$s_time'  order by id desc  ";
$dosql->Execute($sql, 6);
while ($row = $dosql->GetArray(6)) {
    if ($row['fankui'] == 'true' || $row['wanxiu'] == '1' || $row['jiedan'] == 'true' || $row['qiandao'] == 'true' || $row['zhuandan'] == 'true') {
        $order_dongtai[]=[
            'time'=>$row['op_time'],
            'item'=>date("m-d H:i", $row['op_time']) . "   <b style='color: red;'>". $row['op'] . "</b>    <b style='color:lightgreen;'>" . GetMembersName($row['manageid']) . "</b>  [" . $row['orderid'] . "] " . $row['address_name'] . "<br>"
        ];
    }
}

//拜访动态
$sql = "select * from `#@__visit`  where post_time>'$s_time'  order by id desc  ";
$dosql->Execute($sql, 6);
while ($row = $dosql->GetArray(6)) {
        $order_dongtai[]=[
            'time'=>$row['post_time'],
            'item'=>date("m-d H:i", $row['post_time']) . "   <b style='color: red;'>拜访客户</b>    <b style='color:lightgreen;'>" . GetMembersName($row['uid']) . "</b>  [拜访" . $row['id'] . "] " . $row['school'] . "<br>"
        ];
}
# 以二维数组的a作为比较值
$key = array_column(array_values($order_dongtai), 'time');
# 第一个参数需要提供二维数组排序依据
# 第二个排序方式 SORT_ASC:正序 SORT_DESC:倒序
# 第三个参数 要排序的二维数组,改动直接操作在该数组上
# 排序能保证key不改变
array_multisort($key, SORT_DESC, $order_dongtai);

foreach ($order_dongtai as $d_key=>$d_val){
    $dongtai.=$d_val['item'];
}


$errno = array('errno' => 0); //json状态为ok
$json_arr = array('count' => $count, 'order' => $order_list, 'map' => $map, 'order_type' => $order_type, 'managelist' => $managelist,'year_data'=>$year_data,'dongtai'=>$dongtai);
$json_json = array_merge($errno, array('data' => $json_arr));
$data = json_encode($json_json, JSON_UNESCAPED_UNICODE);
echo $data;



//获取前12个月月份
function getTimeAndCenters()
{
    //获取前6个月时间
    $beforeTime = [];
    for ($i = 0; $i < 12; $i++) {
        if ($i == 0) {
            $beforeTime[$i] = date('Y-m');
        } else {
            $base = strtotime(date('Y-m') . '-01 00:00:01');
            $t = "-" . $i . " month";
            $beforeTime[$i] = date('Y-m', strtotime($t, $base));
        }
    }

    return $beforeTime;

}

function getNextMonth($date){
    //获取指定日期下个月的第一天和最后一天
    $arr = getdate(strtotime($date));
    if ($arr['mon'] == 12) {
        $year = $arr['year'] + 1;
        $month = $arr['mon'] - 11;
        $day = $arr['mday'];
        if ($day < 10) {
            $mday = '0' . $day;
        } else {
            $mday = $day;
        }
        $firstday = $year . '-0' . $month . '-01';
        $lastday = $year . '-0' . $month . '-' . $mday;
    } else {
        $time = strtotime($date);
        $firstday = date('Y-m-01', strtotime(date('Y', $time) . '-' . (date('m', $time) + 1) . '-01'));
        $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
    }
    $array = array('sdate' => $firstday, 'edate' => $lastday);
    return $array;
}

//获取工程师当月的积分
function getFeeThisMonth($mid){
    //获取所有的 记录合计
    global $dosql;
    $all_fee="0";
    $sql_order="SELECT * FROM   `#@__fee_log`   WHERE manageid='$mid'  AND  FROM_UNIXTIME(`op_time`,'%Y%m')=DATE_FORMAT(CURDATE(),'%Y%m') ";
    $dosql->Execute($sql_order,7);
    while($order=$dosql->GetArray(7)){
        if($order['op']=='add'){
            $all_fee+=$order['fee'];
        }elseif($order['op']=='move'){
            $all_fee-=$order['fee'];
        }
    }
    return $all_fee;
}

//获取 服务工程师
function getManage($mid){
    global $dosql;
    if($mid>0){
        $m=$dosql->GetOne("SELECT * FROM `#@__user` WHERE id='$mid' ORDER BY id desc");
        if(is_array($m) && isset($m['id']) ){
            return  $m['truename'];
        }
    }

}


/*
 * 函数说明：获取 多个工作人员 的名称
 *
 * @access  public
 * @param   $id   int  碎片ID
 * @param   $t    int  调用的内容 0为内容 1为标识名称 2为缩略图 3为跳转连接
 * @return  string     返回碎片缩略图地址
 */
function GetMembersName($ids = 0)
{
    global $dosql;
    if ($ids != "") {
        $men_names = "";
        $member = explode(",", $ids);
        if (count($member) > 1) {
            $i = 0;
            foreach ($member as $v) {
                $i++;
                if ($i < count($member)) {
                    $men_names .= getManage($v) . " ";
                } else {
                    $men_names .= getManage($v);
                }
            }
        } else {
            $men_names = getManage($ids);
        }
        return $men_names;
    } else {
        return "";
    }
}


//获取任务类型
function getRepairMode($mid){
    global $dosql;
    if($mid>0){
        $m=$dosql->GetOne("SELECT p.`classname`,t.`title` FROM `#@__task` as t left join `#@__tasktype` as p  on t.classid=p.id  WHERE t.id='$mid' ");
        if(is_array($m) && isset($m['title']) ){
            return $m['classname']."-".$m['title'];
        }
    }

}


?>

